package no.mehdi.usereg.web.action;

import java.io.IOException;

import no.mehdi.usereg.core.rfid.RFIDController;
import no.mehdi.usereg.core.service.PersonService;
import no.mehdi.usereg.core.utils.SpringApplicationContext;
import no.mehdi.usereg.web.form.PersonRegisterForm;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.webflow.action.FormAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import com.phidgets.PhidgetException;

public class PersonRegisterAction extends FormAction {
	PersonService personService;
	RFIDController rfidController;
	protected Object createFormObject(RequestContext context) throws Exception {
		context.getRequestParameters();
		return (PersonRegisterForm) super.createFormObject(context);
	}

	public Event save(RequestContext requestContext) throws Exception {
		System.out.println("***"
				+ requestContext.getRequestParameters().get("name"));
		PersonRegisterForm form = (PersonRegisterForm) getFormObject(requestContext);
		personService.registerPerson(form.getName());
		return success();
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}

	public void startListener(RequestContext context) throws Exception {

		try {
			rfidController.startRfid();
		} catch (PhidgetException e) {
			MessageContext messages = context.getMessageContext();		
			messages.addMessage(new MessageBuilder().error().source("RFIDcomponent").code("ss").build());
			System.out.println(messages);
		}
		
	}

	public void setRfidController(RFIDController rfidController) {
		this.rfidController = rfidController;
	}
}
